/*
 * Decompiled with CFR 0.150.
 * 
 * Could not load the following classes:
 *  cn.hutool.core.util.ObjectUtil
 *  de.felixroske.jfxsupport.AbstractFxmlView
 *  de.felixroske.jfxsupport.AbstractJavaFxApplicationSupport
 *  de.felixroske.jfxsupport.GUIState
 *  javafx.application.Platform
 *  javafx.scene.Scene
 *  javafx.scene.control.Alert
 *  javafx.scene.control.Alert$AlertType
 *  javafx.scene.control.ComboBox
 *  javafx.stage.FileChooser
 *  javafx.stage.FileChooser$ExtensionFilter
 *  javafx.stage.Modality
 *  javafx.stage.Stage
 *  javafx.stage.Window
 *  javafx.util.StringConverter
 *  org.apache.poi.hssf.usermodel.HSSFDataFormat
 *  org.apache.poi.hssf.usermodel.HSSFDateUtil
 *  org.apache.poi.openxml4j.exceptions.InvalidFormatException
 *  org.apache.poi.ss.usermodel.Cell
 *  org.apache.poi.ss.usermodel.Row
 *  org.apache.poi.ss.usermodel.Sheet
 *  org.apache.poi.ss.usermodel.Workbook
 *  org.apache.poi.ss.usermodel.WorkbookFactory
 *  org.slf4j.Logger
 *  org.slf4j.LoggerFactory
 *  org.springframework.context.ConfigurableApplicationContext
 *  org.springframework.mock.web.MockMultipartFile
 *  org.springframework.util.StringUtils
 */
package com.gys.common.util;

import cn.hutool.core.util.ObjectUtil;
import com.gys.common.data.HttpJson;
import com.gys.common.data.KeyValue;
import com.gys.common.exception.BusinessException;
import com.gys.common.util.CacheUtil;
import com.gys.common.util.SpringUtil;
import com.gys.controller.index.IndexController;
import de.felixroske.jfxsupport.AbstractFxmlView;
import de.felixroske.jfxsupport.AbstractJavaFxApplicationSupport;
import de.felixroske.jfxsupport.GUIState;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javafx.application.Platform;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.ComboBox;
import javafx.stage.FileChooser;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.Window;
import javafx.util.StringConverter;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.util.StringUtils;

public class CommonUtil {
    private static final Logger log = LoggerFactory.getLogger(CommonUtil.class);
    private static ConfigurableApplicationContext applicationContext = null;

    public static String getFuzzyParam(String param) {
        if (StringUtils.isEmpty(param)) {
            return param;
        }
        return "%" + param + "%";
    }

    public static String getSetMethod(String property) {
        return "set" + property.substring(0, 1).toUpperCase() + property.substring(1);
    }

    public static String getGetMethod(String property) {
        return "get" + property.substring(0, 1).toUpperCase() + property.substring(1);
    }

    public static StringConverter dataPickerFormat(final String pattern) {
        StringConverter<LocalDate> converter = new StringConverter<LocalDate>(){
            DateTimeFormatter dateFormatter;
            {
                this.dateFormatter = DateTimeFormatter.ofPattern(pattern);
            }

            public String toString(LocalDate date) {
                if (date != null) {
                    return this.dateFormatter.format(date);
                }
                return "";
            }

            public LocalDate fromString(String string) {
                if (string != null && !string.isEmpty()) {
                    return LocalDate.parse(string, this.dateFormatter);
                }
                return null;
            }
        };
        return converter;
    }

    public static Alert createAlert(Alert.AlertType alertType, String title, String content) {
        Alert alert = new Alert(alertType);
        alert.setHeaderText(title);
        if (!StringUtils.isEmpty(content)) {
            alert.setContentText(content);
        }
        return alert;
    }

    public static <T> List<T> importExcel(File file, int no, Class<T> t) throws IOException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException, InstantiationException, InvalidFormatException {
        FileInputStream inputStream = new FileInputStream(file);
        MockMultipartFile multipartFile = new MockMultipartFile(file.getName(), (InputStream)inputStream);
        InputStream inp = multipartFile.getInputStream();
        Workbook workbook = WorkbookFactory.create((InputStream)inp);
        Sheet sheet = workbook.getSheetAt(no);
        ArrayList<T> list = new ArrayList<T>();
        Row rowModel = sheet.getRow(1);
        if (rowModel == null) {
            return null;
        }
        for (int i = sheet.getFirstRowNum() + 1; i <= sheet.getLastRowNum(); ++i) {
            Row row = sheet.getRow(i);
            if (row == null) continue;
            T instance = t.newInstance();
            Field[] fields = instance.getClass().getDeclaredFields();
            for (int k = 0; k < fields.length; ++k) {
                Method setMethod = instance.getClass().getMethod("set" + StringUtils.capitalize((String)fields[k].getName()), String.class);
                Cell cell = row.getCell(k);
                if (cell == null) {
                    setMethod.invoke(instance, "");
                    continue;
                }
                if (cell.getCellType() == 0) {
                    String strCell = "";
                    if (HSSFDateUtil.isCellDateFormatted((Cell)cell)) {
                        SimpleDateFormat sdf = null;
                        sdf = cell.getCellStyle().getDataFormat() == HSSFDataFormat.getBuiltinFormat((String)"h:mm") ? new SimpleDateFormat("HH:mm") : new SimpleDateFormat("yyyy-MM-dd");
                        Date date = cell.getDateCellValue();
                        strCell = sdf.format(date);
                    } else {
                        DecimalFormat df = new DecimalFormat("0");
                        strCell = df.format(cell.getNumericCellValue());
                    }
                    setMethod.invoke(instance, CommonUtil.filterSpecialCharacter(strCell.replace(" ", "")));
                    continue;
                }
                if (cell.getCellType() != 1 && cell.getCellType() != 2) continue;
                try {
                    setMethod.invoke(instance, CommonUtil.filterSpecialCharacter(cell.getStringCellValue().replace(" ", "")));
                    continue;
                }
                catch (Exception e) {
                    throw new BusinessException("\u7b2c" + (row.getRowNum() + 1) + "\u884c\uff0c" + (k + 1) + "\u5217\u6570\u636e\u6709\u8bef");
                }
            }
            list.add(instance);
        }
        return list;
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    public static void exportModelFile(String fileName, String modelPath) {
        Stage stage = new Stage();
        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("\u5bfc\u51fa");
        fileChooser.setInitialDirectory(new File(System.getProperty("user.home")));
        fileChooser.setInitialFileName(fileName);
        fileChooser.getExtensionFilters().addAll(new FileChooser.ExtensionFilter[]{new FileChooser.ExtensionFilter("Excel files (*.xls)", new String[]{"*.xls"}), new FileChooser.ExtensionFilter("Allfiles", new String[]{"*.*"})});
        File target = fileChooser.showSaveDialog((Window)stage);
        if (target == null) {
            return;
        }
        InputStream input = CommonUtil.class.getResourceAsStream(modelPath);
        FileOutputStream output = null;
        try {
            int bytesRead;
            output = new FileOutputStream(target);
            byte[] buf = new byte[1024];
            while ((bytesRead = input.read(buf)) != -1) {
                ((OutputStream)output).write(buf, 0, bytesRead);
            }
            output.flush();
            ((OutputStream)output).close();
            input.close();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            try {
                if (input != null) {
                    input.close();
                }
            }
            catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (output != null) {
                    ((OutputStream)output).close();
                }
            }
            catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static File fileChooser() {
        Stage stage = new Stage();
        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("\u5bfc\u5165");
        fileChooser.getExtensionFilters().addAll(new FileChooser.ExtensionFilter[]{new FileChooser.ExtensionFilter("excel files (*.xls)", new String[]{"*.xls"}), new FileChooser.ExtensionFilter("Allfiles", new String[]{"*.*"})});
        File file = fileChooser.showOpenDialog((Window)stage);
        return file;
    }

    public static File imageChooser() {
        String directoryUrl;
        File directory;
        Stage stage = new Stage();
        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("\u9009\u62e9");
        if (ObjectUtil.isNotNull(CacheUtil.get("lastPathDirectory")) && (directory = new File(directoryUrl = (String)CacheUtil.get("lastPathDirectory"))).exists()) {
            fileChooser.setInitialDirectory(directory);
        }
        fileChooser.getExtensionFilters().addAll(new FileChooser.ExtensionFilter[]{new FileChooser.ExtensionFilter("\u56fe\u7247(*.jpg)", new String[]{"*.jpg"}), new FileChooser.ExtensionFilter("\u56fe\u7247(*.png)", new String[]{"*.png"}), new FileChooser.ExtensionFilter("\u56fe\u7247(*.bmp)", new String[]{"*.bmp"})});
        File file = fileChooser.showOpenDialog((Window)stage);
        return file;
    }

    public static String filterSpecialCharacter(String str) {
        str = str.replace(String.valueOf('\u00a0'), " ");
        str = str.replace("\n", "").trim();
        str = str.replace("\r", "").trim();
        str = str.replace("\t", "").trim();
        str = str.replace("\b", "").trim();
        str = str.replace("\f", "").trim();
        str = str.replace("'", "").trim();
        str = str.replace("''", "").trim();
        str = str.replace("\u0000", "").trim();
        return str;
    }

    public static Map<String, Object> convertToMap(Object obj) {
        HashMap<String, Object> map = new HashMap<String, Object>();
        Class<?> clazz = obj.getClass();
        for (Field field : clazz.getDeclaredFields()) {
            field.setAccessible(true);
            String fieldName = field.getName();
            String value = null;
            try {
                Object objVal = field.get(obj);
                if (objVal == null) continue;
                value = String.valueOf(objVal);
            }
            catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            map.put(fieldName, value);
        }
        return map;
    }

    public static boolean handleHttpResOnlyAlert(HttpJson httpJson, String message) {
        Alert alert = CommonUtil.createAlert(Alert.AlertType.INFORMATION, "\u63d0\u793a\u4fe1\u606f", null);
        if (httpJson.isSuccess()) {
            alert.setContentText(message);
            alert.showAndWait();
            return true;
        }
        alert.setContentText(httpJson.getMsg());
        alert.showAndWait();
        return false;
    }

    public static boolean positiveInteger(String str) {
        if (ObjectUtil.isEmpty(str)) {
            return false;
        }
        String theOne = str.substring(0, 1);
        if ("0".equals(theOne) || "-".equals(theOne)) {
            return false;
        }
        Pattern pattern = Pattern.compile("[0-9]*");
        return pattern.matcher(str).matches();
    }

    public static boolean isIDNumber(String IDNumber) {
        if (IDNumber == null || "".equals(IDNumber)) {
            return false;
        }
        String regularExpression = "(^[1-9]\\d{5}(18|19|20)\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}[0-9Xx]$)|(^[1-9]\\d{5}\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}$)";
        boolean matches = IDNumber.matches(regularExpression);
        if (matches) {
            if (IDNumber.length() == 18) {
                try {
                    char[] charArray = IDNumber.toCharArray();
                    int[] idCardWi = new int[]{7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};
                    String[] idCardY = new String[]{"1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2"};
                    int sum = 0;
                    for (int i = 0; i < idCardWi.length; ++i) {
                        int current = Integer.parseInt(String.valueOf(charArray[i]));
                        int count = current * idCardWi[i];
                        sum += count;
                    }
                    char idCardLast = charArray[17];
                    int idCardMod = sum % 11;
                    if (idCardY[idCardMod].toUpperCase().equals(String.valueOf(idCardLast).toUpperCase())) {
                        return true;
                    }
                    System.out.println("\u8eab\u4efd\u8bc1\u6700\u540e\u4e00\u4f4d:" + String.valueOf(idCardLast).toUpperCase() + "\u9519\u8bef,\u6b63\u786e\u7684\u5e94\u8be5\u662f:" + idCardY[idCardMod].toUpperCase());
                    return false;
                }
                catch (Exception e) {
                    e.printStackTrace();
                    return false;
                }
            }
            return false;
        }
        return matches;
    }

    public static void resizableFalse(final Class tclass) {
        new Timer().schedule(new TimerTask(){

            @Override
            public void run() {
                Platform.runLater((Runnable)new Runnable(){

                    @Override
                    public void run() {
                        Scene scene = ((AbstractFxmlView)SpringUtil.getBean(tclass)).getView().getScene();
                        if (ObjectUtil.isEmpty(scene)) {
                            return;
                        }
                        Stage stage = (Stage)scene.getWindow();
                        stage.setResizable(false);
                    }
                });
            }
        }, 1000L);
    }

    public static boolean isLegalDate(String sDate, String formate, int legalLen) {
        if (sDate == null || sDate.length() != legalLen) {
            return false;
        }
        SimpleDateFormat formatter = new SimpleDateFormat(formate);
        try {
            Date date = formatter.parse(sDate);
            return sDate.equals(formatter.format(date));
        }
        catch (Exception e) {
            return false;
        }
    }

    public static String format2(float value) {
        return String.format("%.2f", Float.valueOf(value)).toString();
    }

    public static String format2NoRound(float value) {
        DecimalFormat formater = new DecimalFormat();
        formater.setMaximumFractionDigits(2);
        formater.setGroupingSize(0);
        formater.setRoundingMode(RoundingMode.FLOOR);
        return formater.format(value);
    }

    public static void comboxInit(ComboBox box) {
        box.converterProperty().set(new StringConverter<KeyValue>(){

            public String toString(KeyValue object) {
                return object.getName();
            }

            public KeyValue fromString(String string) {
                return null;
            }
        });
    }

    public static boolean checkPhone(String phone) {
        Pattern p = Pattern.compile("^((19[0-9])|(13[0-9])|(15[^4,\\D])|(18[0-9]))\\d{8}$");
        Matcher m = p.matcher(phone);
        return m.matches();
    }

    public static void showView(Class<? extends AbstractFxmlView> window, Modality mode) {
        if (ObjectUtil.isEmpty(applicationContext)) {
            Field[] fields = AbstractJavaFxApplicationSupport.class.getDeclaredFields();
            try {
                for (Field field : fields) {
                    field.setAccessible(true);
                    if (!"applicationContext".equals(field.getName())) continue;
                    applicationContext = (ConfigurableApplicationContext)field.get(AbstractJavaFxApplicationSupport.class);
                }
            }
            catch (Exception e) {
                e.printStackTrace();
            }
        }
        AbstractFxmlView view = (AbstractFxmlView)applicationContext.getBean(window);
        Stage newStage = new Stage();
        Scene newScene = view.getView().getScene() != null ? view.getView().getScene() : new Scene(view.getView());
        newStage.setScene(newScene);
        newStage.initModality(mode);
        newStage.initOwner((Window)IndexController.stage);
        newStage.showAndWait();
    }

    public static void showView(Class<? extends AbstractFxmlView> window, Modality mode, String title) {
        if (ObjectUtil.isEmpty(applicationContext)) {
            Field[] fields = AbstractJavaFxApplicationSupport.class.getDeclaredFields();
            try {
                for (Field field : fields) {
                    field.setAccessible(true);
                    if (!"applicationContext".equals(field.getName())) continue;
                    applicationContext = (ConfigurableApplicationContext)field.get(AbstractJavaFxApplicationSupport.class);
                }
            }
            catch (Exception e) {
                e.printStackTrace();
            }
        }
        AbstractFxmlView view = (AbstractFxmlView)applicationContext.getBean(window);
        Stage newStage = new Stage();
        Scene newScene = view.getView().getScene() != null ? view.getView().getScene() : new Scene(view.getView());
        newStage.setScene(newScene);
        newStage.initModality(mode);
        newStage.setTitle(title);
        newStage.initOwner((Window)IndexController.stage);
        newStage.showAndWait();
    }

    public static String getSecondTimestampTwo(Date date) {
        if (null == date) {
            return "0";
        }
        String timestamp = String.valueOf(date.getTime() / 1000L);
        return timestamp;
    }

    public static String bigDecimalTo2fStr(BigDecimal money) {
        DecimalFormat decimalFormat = new DecimalFormat("##########.##########");
        return String.format("%.2f", Float.valueOf(decimalFormat.format(money)));
    }

    public static void initIcon(final Class abstractFxmlView) {
        Platform.runLater((Runnable)new Runnable(){

            @Override
            public void run() {
                Stage stage = (Stage)((AbstractFxmlView)SpringUtil.getBean(abstractFxmlView)).getView().getScene().getWindow();
                stage.getIcons().addAll((Collection)GUIState.getStage().getIcons());
            }
        });
    }
}

